package com.yc.home.cloudother.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.bean.Result;
import com.yc.entity.Classs;
import com.yc.entity.Createclass;
import com.yc.home.cloudother.mapper.ClasssMapper;
import com.yc.home.cloudother.mapper.CreateclassMapper;
import com.yc.home.cloudother.service.IClasssService;
import com.yc.home.cloudother.service.ICreateclassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzk
 * @since 2024-10-05
 */
@RestController
@RequestMapping("/createclass")
public class CreateclassController {

    @Autowired
    CreateclassMapper createclassMapper;

    //查询班级
    @RequestMapping("mycreate")
    Result mycreate(String id){
        LambdaQueryWrapper<Createclass> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Createclass::getUid, id);
        lqw.eq(Createclass::getStatus, 1);
        List<Createclass> createclasses = createclassMapper.selectList(lqw);
        return new Result(1, "我创建的班级", createclasses);
    }

    @Autowired
    ClasssMapper classsMapper;

    //创建班级
    @Transactional          //事务注解
    @RequestMapping("createClass")
    public Result createClass(String id, String name){
        try{
            //创建班级
            Createclass createclass = new Createclass();
            // 生成邀请码
            String code = generateUniqueCode();
            createclass.setCname(name);
            createclass.setUid(Integer.valueOf(id));
            createclass.setNum(code);
            createclass.setImage("http://127.0.0.1/cloud-other/image/3c4f7322-a7f7-4e17-a0d2-540f4dc35236.jpg");
            createclass.setStatus(1);
            createclassMapper.insert(createclass);
            //老师加入班级
            LambdaQueryWrapper<Createclass> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Createclass::getNum, code);
            Createclass createclass1 = createclassMapper.selectOne(lqw);
            Classs classs = new Classs();
            classs.setCid(createclass1.getId());
            classs.setUid(Integer.valueOf(id));
            classs.setSayname("班主任");
            classs.setStatus(2);
            classsMapper.insert(classs);
            return new Result(1, "创建成功", null);
        }catch (Exception e){
            return new Result(0, "创建失败!", null);
        }
    }

    @Autowired
    ICreateclassService iCreateclassService;

    @Autowired
    IClasssService iClasssService;

    @RequestMapping("add")
    Result add(String id, String code, String sayname){
        //查询code邀请码
        Result result = iCreateclassService.opinionCode(code);
        if(result.getCode() == 0){
            return result;
        }
        Object data = result.getData();
        //加入班级
        return iClasssService.addClass(id, data.toString(), sayname);
    }

    //关联查询学生
    @RequestMapping("getstudy")
    Result getstudy(String id){
        Createclass createclass = createclassMapper.byIdClass(id);
        for (Classs classObj : createclass.getClassobj()) {
            String userImage = classsMapper.getimage(String.valueOf(classObj.getUid())); // 假设这是获取用户头像的方法
            classObj.setImage(userImage); // 假设Classs类有一个setUserImage方法来设置用户头像
        }
        return new Result(1, "学生信息", createclass);
    }

    //关联审核学生
    @RequestMapping("getaudit")
    Result getaudit(String id){
        Createclass createclass = createclassMapper.byIdAudit(id);
        for (Classs classObj : createclass.getClassobj()) {
            String userImage = classsMapper.getimage(String.valueOf(classObj.getUid())); // 假设这是获取用户头像的方法
            classObj.setImage(userImage); // 假设Classs类有一个setUserImage方法来设置用户头像
        }
        return new Result(1, "学生信息", createclass);
    }

    //修改班级名称
    @RequestMapping("updateClassName")
    Result updateClassName(String cid, String newName){
        try{
            Createclass createclass = createclassMapper.selectById(cid);
            createclass.setCname(newName);
            createclassMapper.updateById(createclass);
            return new Result(1, "修改成功", null);
        }catch (Exception e){
            return new Result(0, "连接超时，请稍后再试！", null);
        }
    }

    //修改群头像
    @RequestMapping("updateClassImage")
    Result updateClassImage(String cid, String image){
        try{
            Createclass createclass = createclassMapper.selectById(cid);
            createclass.setImage(image);
            createclassMapper.updateById(createclass);
            return new Result(1, "修改群头像成功", null);
        }catch (Exception e){
            return new Result(0, "连接超时，请稍后再试！", null);
        }
    }















    //生成邀请码
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int INVITATION_CODE_LENGTH = 6;

    // 模拟检查邀请码是否已存在的方法（实际中应查询数据库）
    private boolean isCodeExisting(String code) {
        LambdaQueryWrapper<Createclass> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Createclass::getNum, code);
        Long aLong = createclassMapper.selectCount(lqw);
        if(aLong > 0){
            return true;
        }
        return false;
    }

    // 生成邀请码的方法
    public String generateUniqueCode() {
        String code;
        do {
            code = generateRandomCode();
        } while (isCodeExisting(code));
        return code;
    }

    // 生成随机6位邀请码的方法
    private String generateRandomCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(INVITATION_CODE_LENGTH);
        for (int i = 0; i < INVITATION_CODE_LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    @Autowired
    RestTemplate restTemplate;

    //解散群聊
    @Transactional
    @RequestMapping("exitAll")
    public Result exitAll(int cid){
        //班级成员
        LambdaQueryWrapper<Classs> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Classs::getCid, cid);
        classsMapper.delete(lqw);
        createclassMapper.deleteById(cid);
        //去调用user模块的service层的删除方法
        // 调用user服务的API
        String userServiceUrl = "http://cloud-user/chat/all?cid="+ cid; // 确保URL正确，并且服务可访问

        ResponseEntity<Result> response = restTemplate.getForEntity(userServiceUrl, Result.class);

        // 处理user服务的响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Result userServiceResult = response.getBody();
            return new Result(1, "解散成功", null);
        } else {
            // 处理调用失败的情况
            return new Result(0, "调用用户服务失败", null);
        }
    }

    @RequestMapping("getclass")
    Page getclass(@RequestParam(defaultValue = "1") int currentPage4, @RequestParam(defaultValue = "10") int pagesize, String id, String cname, String num, String status){
        Page<Createclass> page = new Page<>(currentPage4, pagesize);
        LambdaQueryWrapper<Createclass> lqw = new LambdaQueryWrapper<>();
        if(!"".equals(id)){
            lqw.eq(Createclass::getId, id);
        }
        if(!"".equals(cname)){
            lqw.like(Createclass::getCname, cname);
        }
        if(!"".equals(num)){
            lqw.eq(Createclass::getNum, num);
        }
        if(!"2".equals(status)){
            lqw.eq(Createclass::getStatus, status);
        }
        return createclassMapper.selectPage(page, lqw);
    }

    @RequestMapping("ban")
    Result ban(String id){
        Createclass createclass = createclassMapper.selectById(id);
        createclass.setStatus(0);
        createclassMapper.updateById(createclass);
        return new Result(1, "成功", null);
    }

    @RequestMapping("noban")
    Result noban(String id){
        Createclass createclass = createclassMapper.selectById(id);
        createclass.setStatus(1);
        createclassMapper.updateById(createclass);
        return new Result(1, "成功", null);
    }

}

